module.exports = (sequelize, DataTypes) => {
  const Category = sequelize.define('Category', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    user_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'users',
        key: 'id'
      }
    },
    name: {
      type: DataTypes.STRING(50),
      allowNull: false,
      validate: {
        len: [1, 50],
        notEmpty: true
      }
    },
    description: {
      type: DataTypes.TEXT,
      allowNull: true
    },
    color: {
      type: DataTypes.STRING(7),
      defaultValue: '#1890ff',
      validate: {
        is: /^#[0-9A-Fa-f]{6}$/i // 验证十六进制颜色值
      }
    },
    icon: {
      type: DataTypes.STRING(50),
      allowNull: true,
      comment: 'emoji或图标类名'
    }
  }, {
    tableName: 'categories',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    charset: 'utf8mb4',
    collate: 'utf8mb4_general_ci',
    indexes: [
      {
        fields: ['user_id']
      },
      {
        unique: true,
        fields: ['user_id', 'name'],
        name: 'unique_user_category'
      }
    ]
  });

  Category.associate = (models) => {
    // 分类属于用户
    Category.belongsTo(models.User, {
      foreignKey: 'user_id',
      as: 'user',
      onDelete: 'CASCADE'
    });

    // 分类有多篇日记
    Category.hasMany(models.Diary, {
      foreignKey: 'category_id',
      as: 'diaries',
      onDelete: 'SET NULL'
    });
  };

  return Category;
}; 